const Service = require("egg").Service;

class CommodityService extends Service {
  async findList(query) {
    let { pageSize, currentPage } = query;
    pageSize = pageSize || 10;
    currentPage = currentPage || 1;
    if (query.name) {
      return await this.ctx.model.Commodity.find({
        name: {
          $regex: query.name
        }
      })
        .populate("menuId")
        .limit(+pageSize)
        .skip((+currentPage - 1) * pageSize)
        .sort({
          sort: -1
        });
    } else {
      return await this.ctx.model.Commodity.find({})
        .populate("menuId")
        .limit(+pageSize)
        .skip((+currentPage - 1) * pageSize)
        .sort({
          sort: -1
        });
    }
    // 这里如果不需要分页 直接返回所有的栏目信息
    if (query.noPage) {
      return await this.ctx.model.Commodity.find({})
        .populate("menuId")
        .sort({ sort: -1 });
    }
  }

  async fetchAll(){
    return await this.ctx.model.Commodity.find({});
  }


  // 新增
  async add(commodity) {
    return await this.ctx.model.Commodity.create(commodity);
  }

  async findAll() {
    return await this.ctx.model.Commodity.find({})
      .populate("menuId")
      .sort({
        sort: -1
      });
  }

  // 修改
  async update(commodity) {
    return await this.ctx.model.Commodity.findOneAndUpdate(
      {
        _id: commodity._id
      },
      commodity
    );
  }

  // 批量删除
  async delete(_ids) {
    return await this.ctx.model.Commodity.deleteMany({
      _id: {
        $in: _ids
      }
    });
  }

  async deleteAll() {
    const foods = await this.ctx.model.Commodity.find({});
    let ids = [];
    foods.map(item => {
      ids.push(item._id);
    });
    const ret = await this.ctx.model.Commodity.deleteMany({
      _id: { $in: ids }
    });
  }

  async findById(_id) {
    return await this.ctx.model.Commodity.find({
      tabId: _id
    });
  }
  // 这里是模糊查询
  async search(query) {
    if (query) {
      return await this.ctx.model.Commodity.find({
        name: { $regex: query }
      })
        .populate("menuId")
        .sort({ sort: -1 });
    }
  }
}

module.exports = CommodityService;
